package router

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/julienschmidt/httprouter"
	defs "github.com/lierdan/golangweb/internal/defs"
	resp "github.com/lierdan/golangweb/internal/response"
)

// ...
func Name(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	name := p.ByName("name")
	w.Write([]byte("your name:" + name))
}

// GET
func RegisterUsersGet(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	r.ParseForm()
	name := r.Form["name"]
	password := r.Form["password"]

	if len(name) == 0 || len(password) == 0 {
		resp.SendErrorResponse(w, defs.ErrorRequestBodyParseFailed)
		return
	}

	w.Write([]byte("name:" + name[0] + "password:" + password[0]))
}

// POST
func RegisterUsersPost(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	r.ParseForm()
	name := r.Form["name"]
	password := r.Form["password"]

	if len(name) == 0 || len(password) == 0 {
		resp.SendErrorResponse(w, defs.ErrorRequestBodyParseFailed)
		return
	}

	w.Write([]byte("name:" + name[0] + "password:" + password[0]))
}

// JSON
func RegisterUsersPOSTByJSON(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	bytes, _ := ioutil.ReadAll(r.Body)
	userinfo := &defs.User{}

	err := json.Unmarshal(bytes, userinfo)

	if err != nil {
		resp.SendErrorResponse(w, defs.ErrorRequestBodyParseFailed)
		return
	}

	fmt.Println(userinfo)
	w.Write(bytes)
}
